<?php

namespace app\api\controller\v1;

use app\api\model\Category;
use think\Db;
use think\Request;

class Categories extends Comment
{
    /**
     * 商品分类列表数据
     *
     * @return \think\Response
     */
    public function index()
    {
        $type = Request()->param('type');

        if($type === '1' || $type === '2' || $type === '3' || $type === ''){
            if(empty($this->pageNum) || empty($this->pageSize)){
                $list = Db::name('category')
                    ->field('cat_id,cat_name,cat_pid,cat_level,cat_deleted')
                    ->select();

                if(empty($list)){
                    return $this->out([],'无数据','400');
                }

                return $this->getGoods($list,$type);
            }

            $list = Db::name('category')
                ->field('cat_id,cat_name,cat_pid,cat_level,cat_deleted')
                ->page($this->pageNum,$this->pageSize)
                ->select();

            if(empty($list)){
                return $this->out([],'无数据','400');
            }

            return $this->getGoods($list,$type);
        }else{
            return $this->out([],'type参数错误',422);
        }
    }

    /**
     * 添加分类
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = Request()->param();

        if($data['cat_pid'] === '0'){
            if($data['cat_level'] !== '0'){
                return $this->out([],'分类层级错误',422);
            }
        }

        $id = Category::create($data)->id;

        $res = Db::name('category')
            ->where('cat_id',$id)
            ->field('cat_id,cat_name,cat_pid,cat_level')
            ->find();

        if(empty($res)){
            return $this->out([],'创建失败',400);
        }

        return $this->out($res,'创建成功',200);
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
